import axios from 'axios'
import { toast } from '~/composables/util'
import { getToken } from '~/composables/auth'
import router from './router/index.js'
import store from '~/store'
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: "/api"
        // baseURL: import.meta.env.VITE_APP_BASE_API
        // baseURL: import.meta.env.VITE_APP_BASE_API
})

// request拦截器
service.interceptors.request.use(config => {
    const token = getToken()
    if (token) {
        config.headers['token'] = token
    }
    return config
}, error => {
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
        if ((res.config.config && res.config.config.yuan)) {
            return res
        }
        if (res.data.code == 400) {
            return toast(res.data.msg, "error")
        };
        if (res.data.code == 500) {
            localStorage.removeItem("token")
            router.push("/login")
        };
        // console.log(res, 'resresresresresresres');
        // return res.request.responseType == "blob" ? res.data : res.data.data
        return res.data
    },
    error => {
        let code = error.response.data.errorCode
        if (code == 40000 || code == 20000) {
            return toast('因权限问题无法操作', "error")
        }
        // console.log(error.response.data.errorCode);
        let msg = error.response.data.msg || "请求失败"
        if (msg == "非法token，请先登录！") {
            store.dispatch("logout").finally(() => location.reload())
        }
        toast(msg, "error", error.response.data.errorCode == 40000)

        return Promise.reject(error)
    }
)

export default service;